require('./index.scss');
var Config = require('common/config');
var Tool = require('common/tool');
require('comp/tab');
require('comp/dialog');
var page ;

var vm = avalon.define({
    $id: 'extract',
    lang: _language=='zh' ? 'CN':'TW',
    step:1,                                     // 1 第一步 填写存款信息  2 第二步 确认存款信息
    submitLoad:false,
    queryLoad:true,
    refreshLoading:false,                        // 刷新可取资金的加载效果
    withdrawalNum:0,                            // 取款提案数
    accountAmount:'',                           // 账户可取资金
    accountInfo:'',                             //账号信息
    accTradeInfoList:'',                        //账号列表
    bankInfoList:'',                            //银行列表
    currencyList:'',                            //币种列表
    rateMap:'',                                 //汇率列表
    feeInfo:'',                                 //手续费信息
    transAmount:'',                             //取款金额
    
    selAccount:{},                              // 选中的账号
    selPlatform:'',                              // 选中账号的平台
    selBank:{},                                 // 选中的银行
    selBankCode:'',                             // 选中的银行code
    selCurrency:{},                             // 选中的入账币种 对象
    selCurrencyCode:'',                         // 选中的入账币种
    rate:'',                                    //汇率
    remark:'',                                  //备注
    valid:false,                                //是否需要验证码
    validLoad:false,                            //获取验证码等待
    validLoadTime:'',                           //获取验证码间隔时间
    validCode:'',                               //验证码
    // 兑换汇率注意事项 
    rateDialog:{
        display:"none",
        title: '兑换汇率注意事项',
    },
    // 手续费弹窗
    feeDialog:{
        display:"none",
        title: '手续费提示明细',
        thList:[
            {label:'项目', text:"content"},
            {label:'手续费', text:"fee"}
        ],
        list:'',
    },
    // 活动记录弹窗
    acRecordDialog:{
        display:"none",
        title: '活动记录',
        thList:[
            {label:'活动名称', text:"eventName"},
            {label:'活动内容', text:"displayName"},
            {label:'记录状态', text:"displayNameCn"},
            {label:'先赠赠金', text:"givenBonus", className:"primary"},
            {label:'已释放赠金', text:"releasedBonus", className:"primary"},
            {label:'将扣除赠金', text:"bonusOutAmount", className:"primary"}
        ],
        list:'',
    },
    extractActivity:'',                         // 取款活动
    customerLink: Config.CustOnline,             //在线客服
    /* 限制取款金额只能输入数字 */
    transAmountInput:function(e){
        console.log(e.target.value);
        var str = e.target.value.replace(/\D+/g,'');
        e.target.value = str;
    },
    /* 输入取款金额 更新显示手续费 */
    inputAmount: function () {
        vm.feeInfo ='';
        page.queryFeeInfo();
    },
    resetFn:function(){
        this.remark = '';
        this.feeInfo = '';
        this.transAmount = '';
    },
    /* 点击提交验证取款信息 */
    submitfn:function(){
        var transAmount = vm.transAmount.trim();
        if( transAmount=='' || isNaN(transAmount) ){
            layer.alert('请输入取款金额');
            return false;
        }

        page.queryCheckExtract();
    },
    confirmSubmit:function(){
        page.submitExtract();
    },
    /** 切换 select 下拉列表
     *  @param {Array} _list  数据列表
     *  @param {String} _duplex  select双向数据绑定的字段
     *  @param {String} _key  _list列表里面用于和_duplex进行比较的字段名称
     *  @param {String} _sel  当前选中的_list列表某一组数据
     */
    changeSelect:function(_list, _duplex, _key, _sel){
        setTimeout(function(){
            vm[_list].forEach(function(v,i){
                if(v[_key] == vm[_duplex]){
                    vm[_sel] = v;
                    return false;
                }
            }); 
            if(_duplex === 'selPlatform') page.queryAmount();
            if(_duplex === 'selCurrencyCode' && vm.transAmount){
                 caculate_payAmount();
            } 
        },0);
    },
    refreshFn:function(){
        page.queryAmount();
    },

    /* 获取验证码 */
    getValidCode:function(e){
        if(vm.validLoad == true) return;
        vm.validLoad = true;
        Tool.ajax({
            url: '/sendValidateCode',
            type:"post"
        }).done(function(res){

            vm.validLoadTime = 60;
            var loopTime = setInterval(function(){
                vm.validLoadTime--;
                if(vm.validLoadTime==0){
                    clearInterval(loopTime);
                    vm.validLoadTime='';
                    vm.validLoad = false;
                }
            },1000);
        });
    }
});

vm.$watch('onReady',function(){
    page = new Extract();
    window['vm'] = vm;
});

/* 监听账号币种和入账币种，更新汇率 */
vm.$watch('selAccount.currency',function(v){
    console.log('selAccount.currency',v);
    vm.rate = vm.rateMap[v+vm.selCurrencyCode];
    
});
vm.$watch('selCurrencyCode',function(v){
    console.log('selCurrencyCode',v);
    vm.rate = vm.rateMap[vm.selAccount.currency+v];
});

//入账金额 =  系统汇率*(取款金额-手续费)
function caculate_payAmount(){
    var _caculation = vm.rate * (Number(vm.transAmount) - vm.feeInfo.totalFee );
    vm.feeInfo.payAmount = _caculation.toFixed(2);
}

function Extract(){
    this.queryInfo();
    this.queryDict();
    this.queryWithdrawalNum();
    this.queryExtractActivity();
}

// 获取取款页面信息
Extract.prototype.queryInfo = function(){
    var that = this;
    Tool.ajax({
        url: '/fundDrawings',
        type:"post"
    }).done(function(res){
        vm.queryLoad = false;

        var data = res.data,
            firstWithDraw = data.firstWithDraw,
            validateDepositFile = data.validateDepositFile,
            validateFile = data.validateFile;
        redirectUrl(firstWithDraw, validateFile, validateDepositFile);

        vm.accountInfo = data.accountInfo;
        vm.rateMap = data.rateMap;
        vm.accTradeInfoList = data.accountInfo.accTradeInfoList;
        vm.bankInfoList = data.bankInfoList;
        
        vm.selAccount = data.accountInfo.accTradeInfoList[0];
        vm.selPlatform = data.accountInfo.accTradeInfoList[0].platform;
        vm.selBank = data.bankInfoList[0];
        vm.selBankCode = data.bankInfoList[0].bank;

        // 获取可取资金
        that.queryAmount();
    });
}

/* 检查文件是否上传 */
function redirectUrl(firstWithDraw, validateFile, validateDepositFile){
    if( firstWithDraw=='true' && !validateFile ){
        layer.open({
            title: '提示',
            closeBtn:false,
            content: '请先添加银行资料及完成个人资料、银行资料的验证，再进行取款！',
            yes: function(index, layero){
                stateman.go('account.infofiles');
                layer.close(index); //如果设定了yes回调，需进行手工关闭
            }
        }); 
    }else if( firstWithDraw=='true' && !validateDepositFile ){
        layer.open({
            title: '提示',
            closeBtn:false,
            content: '请先上传存款证明文件，再进行取款！',
            yes: function(index, layero){
                stateman.go('account.uploadDeposit');
                layer.close(index); //如果设定了yes回调，需进行手工关闭
            }
        }); 
    }
}

// 获取数据字典配置接口
Extract.prototype.queryDict = function(){
    var that = this;
    Tool.ajax({
        url: '/getDictConfigInfo',
        data:{
            dictCode:"BankCurrency"
        },
        type:"post"
    }).done(function(res){

        var data = res.data;
        vm.currencyList = data.BankCurrency;        //币种
        vm.selCurrency = data.BankCurrency[0];
        vm.selCurrencyCode = data.BankCurrency[0].code;
    });
}

// 刷新可用余额
Extract.prototype.queryAmount = function(){
    var that = this;
    if(vm.refreshLoading == true) return;
    vm.refreshLoading = true;
    Tool.ajax({
        url: '/getAdvisableCredit',
        data:{
            gts2AccountId: vm.selAccount.gts2AccountId
        },
        type:"post"
    }).done(function(res){
        vm.refreshLoading = false;

        var data = res.data;
        vm.accountAmount = data.advisableCredit;
    });
}

// 获取取款提案
Extract.prototype.queryWithdrawalNum = function(){
    var that = this;
    Tool.ajax({
        url: '/getWithDrawalList',
        type:"post"
    }).done(function(res){

        var data = res.data;
        vm.withdrawalNum = data.withdrawalNum;
    });
}

// 手续费列表接口
Extract.prototype.queryFeeInfo = function(){
    var that = this;
    
    Tool.ajax({
        url: '/fundDrawingsFeeAjax',
        data:{
            gts2AccountId: vm.selAccount.gts2AccountId,
            accountNo: vm.selAccount.accountNo,
            platform: vm.selAccount.platform,
            exchangeRate: vm.rate,
            transAmount: vm.transAmount
        },
        type:"post"
    }).done(function(res){

        var data = res.data;
        vm.feeInfo = data;
        caculate_payAmount();
        // for(var i=0; i<20; i++){
        //     data.tipList.push(data.tipList[0]);
        // };
        vm.feeDialog.list = data.tipList;
    });
}

// 取款信息验证
Extract.prototype.queryCheckExtract = function(_confirm){
    var that = this;
    if( !vm.extractActivity ){
        layer.alert('正在检测是否存在取款活动，请5s后再提交。');
        return false;
    }
    var _params = {
        gts2AccountId: vm.selAccount.gts2AccountId,
        accountNo: vm.selAccount.accountNo,
        platform: vm.selAccount.platform,
        transAmount: vm.transAmount,
        advisableCredit: vm.accountAmount,
        payAmount: vm.feeInfo.payAmount,
        transCurrency: vm.selCurrency.currency,
        exchangeRate: vm.rate,
        remark: vm.remark,
        withdrewBankName: vm.selBankCode,
        withdrewBankAccount: vm.selBank.bankAccountNumber
    }; 

    /* 当存在活动时，用户点击确定按钮，增加valid字段 */
    if( _confirm ) _params.valid = 'not empty';

    if(vm.submitLoad == true) return ;
    vm.submitLoad = true;
    Tool.ajax({
        url: '/fundDrawingsCheckAjax',
        data:_params,
        type:"post"
    }).done(function(res){
        vm.submitLoad = false;

        var data = res.data;
        if( data.valid ){
            var str = '若您申请取款，则'+vm.extractActivity.accoutShecmeList.length;
            str +='个活动资格将会被取消，同时已赠送的金额（'+vm.extractActivity.sumBonusOutAmount+vm.extractActivity.currenyName;
            str +='）将从账户中扣除。您确定要继续取款吗？';
            layer.confirm(str,function(index){
                that.queryCheckExtract(true);
                layer.close(index);
            });
        }else{
            vm.step=2;
        }
        if(data.needSms) vm.valid = true;
    });
}
// 取款确定接口
Extract.prototype.submitExtract = function(_confirm){
    var that = this;

    if( vm.valid && !vm.validCode ){
        layer.alert('请输入验证');
        return false;
    }
    var _params = {
        gts2AccountId: vm.selAccount.gts2AccountId,
        accountNo: vm.selAccount.accountNo,
        platform: vm.selAccount.platform,
        transAmount: vm.transAmount,
        advisableCredit: vm.accountAmount,
        payAmount: vm.feeInfo.payAmount,
        transCurrency: vm.selCurrency.code,
        exchangeRate: vm.rate,
        remark: vm.remark,
        withdrewBankName: vm.selBankCode,
        withdrewBankAccount: vm.selBank.bankAccountNumber,
        validateCode: vm.validCode
    }; 

    if(vm.submitLoad == true) return ;
    vm.submitLoad = true;
    Tool.ajax({
        url: '/fundDrawingsSubmit',
        data:_params,
        type:"post"
    }).done(function(res){
        vm.submitLoad = false;

        var data = res.data;
        stateman.nav('/extract/result?amount='+vm.transAmount+'&currency='+vm.selCurrency.code);
    });
}

// 取款，转账，升降级活动参加赠金活动接口
Extract.prototype.queryExtractActivity = function(){
    var that = this;
    Tool.ajax({
        url: '/shecmRecode',
        data:{
            gts2AccountId: vm.selAccount.gts2AccountId,
            operType: 'pc',
            category: 'withdraw',
        },
        type:"post"
    }).done(function(res){

        var data = res.data;
        vm.extractActivity = data;
        if(data.accoutShecmeList.length>0){
            data.accoutShecmeList.unshift({
                displayName:"",
                eventName:"",
                displayNameCn:"",
                givenBonus:data.sumGivenBonus,
                bonusOutAmount:data.sumBonusOutAmount,
                releasedBonus:data.sumReleasedBonus,
            });
        }
        vm.acRecordDialog.list = data.accoutShecmeList;
    });
}








